package com.friend.chat.media.pressAudio

import android.content.Context
import android.util.Log

import com.friend.chat.websocket.WebSocketManager.Companion.instance

import com.google.gson.Gson
import com.friend.chat.websocket.ChatMessageBean
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream


/**
 * @author batie fancy
 * @des
 * @date 2023/2/27
 */


fun receiveFile(chatMessageBean: ChatMessageBean, context: Context) {
    val fileOutputStream = FileOutputStream(context.cacheDir.toString() + "test1.png")
    if (chatMessageBean.type == 4) {
        val messageStreamBody = Gson().fromJson(chatMessageBean.message.toString(),MessageStreamBody::class.java)
        val buf = messageStreamBody.buf
        val read = messageStreamBody.read
        Log.e("--->", read.toString() + "")
        val off = messageStreamBody.off
        fileOutputStream.write(buf, 0, read)
    }
}

fun sendFile(file: File,chatMessageBean: ChatMessageBean){
    val buf = ByteArray(1024)
    val fileInputStream = FileInputStream(file.path)
    var read = 0
    val off = 0
    var passedLen = 0
    val fileSize: Long = file.length()
    val messageStreamBody = MessageStreamBody()
    messageStreamBody.fileSize = fileSize
    while (fileInputStream.read(buf).also { read = it } != -1) {
        messageStreamBody.buf = buf
        messageStreamBody.off = 0
        messageStreamBody.read = read
        chatMessageBean.message = messageStreamBody
        instance.sendMessage(Gson().toJson(chatMessageBean))
        passedLen += read
        Thread.sleep(300)
    }
    Log.e("文件读写-->", read.toString() + "")
}